#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <taskLib.h>
#include "Api7841.h"
#include "Commdef.h"
static void DumpCanPacket(int iCardNo, int iPortNo, CAN_PACKET *pPacket)
{
	int i;
	printf("CAN Message Dumping, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
	printf("\tCAN ID: %08X\n", pPacket->canId);
	printf("\tRTR: %d\n", pPacket->rtr);
	printf("\tLength: %d\n", pPacket->len);
	printf("\tData: ");
	for (i = 0; i < 8; ++i)
	{
		printf("%02X", pPacket->data[i]);
	}
	printf("\n\n");
}
void OpenPort(int iCardNo, int iPortNo)
{ 
	int iHandle = CanOpenDriver(iCardNo, iPortNo); 
	if (iHandle == -1)
	{
		printf("\n CAN Open Failed, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
	}
	else
	{
		printf("\n CAN Open Succeed, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
	}
}

void ClosePort(int iCardNo, int iPortNo)
{
	int iHandle = iCardNo * 2 + iPortNo;
	CanCloseDriver(iHandle);
}

void WritePack(int iCardNo, int iPortNo)
{
	CAN_PACKET sndPacket;
	int iRetVal;
	int i;
	int iHandle = iCardNo * 2 + iPortNo;
	
	sndPacket.rtr = 0;
	sndPacket.len = 8;
	sndPacket.canId = 0x01;/*iIdCounter++;*/
	for (i = 0; i < 8; ++i)
	{
		sndPacket.data[i] = i+3;/*iDataCounter++*/;
	}
	CanClearRxBuffer(iHandle);
	CanClearTxBuffer(iHandle);
	iRetVal = CanSendMsg(iHandle, &sndPacket);
	if (iRetVal != -1)
	{
		printf("CAN Message send succeed\n");
		/*DumpCanPacket(iCardNo, iPortNo, &sndPacket);*/
	}
}

void ReadPack(int iCardNo, int iPortNo)
{
	int iHandle = iCardNo * 2 + iPortNo;
	int i;
	CAN_PACKET recvPacket;
	int iRetVal;
	int iRecvCnt;
	
	//CanClearRxBuffer(iHandle);
	/*CanClearTxBuffer(iHandle);*/
	
	iRecvCnt = CanGetRcvCnt(iHandle);
	
	//printf("iRecvCnt:%d\n",iRecvCnt);
	for(i = 0; i < iRecvCnt; i++)
	{
		iRetVal = CanRcvMsg(iHandle, &recvPacket);
		if (iRetVal != -1)
		{
			DumpCanPacket(iCardNo, iPortNo, &recvPacket);
		}
		else
		{
			printf("CAN Read Message Failed, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
			//break;
		}	
	}
}
